package com.qdxht.dispenser.utils;

import android.os.Environment;
import android.text.TextUtils;

import androidx.appcompat.app.AppCompatActivity;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.OnDownloadListener;
import com.hjq.http.model.HttpMethod;
import java.io.File;

public class DownloadUtil {

    /** URL:文件存放路径 */
    public static final String URL_FILE_PATH = Environment.getExternalStorageDirectory()+"/dispenser/";

    public static void download(AppCompatActivity mContext, String url, OnDownloadListener listener){
//        String name = url.substring(url.lastIndexOf("/") + 1);
        String name = System.currentTimeMillis()+".apk";
        File savePath = getFile(URL_FILE_PATH);
        File file = new File(savePath, name);
        EasyHttp.download(mContext)
                .method(HttpMethod.GET)
                .file(file)
                .url(url)
                .listener(listener).start();
    }

    /**
     * 删除指定目录下文件及目录
     * @param deleteThisPath
     * @return
     */
    public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件，删除
                        file.delete();
                    } else {// 目录
                        if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取文件夹，不存在则创建
     * @param path
     * @return
     */
    public static File getFile(String path) {
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        return file;
    }
}
